<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app"></div>
  <script>
    /**
     *  type: 标签名称
     *  props: 标签属性
     *  children: 子节点
     *  */
    function createElement(type, props, children) {
      return new Element(type, props, children)
    }

    class Element {
      constructor(type, props, children) {
        this.type = type
        this.props = props
        this.children = children
      }
    }

    function render(vir, root) {
      // 解构
      const { type, props, children } = vir
      // 创建真实节点
      const el = document.createElement(type)
      // 遍历属性
      // Object.entries 返回一个二维数组  小数组第一项是键名 第二项是键值
      // 直接解构赋值
      Object.entries(props).forEach(([key, value] /* 解构数组 */) => {
        setAttr(key, value, el)
      })
      // 遍历子元素
      children.forEach(v => {
        console.log(v);
        if(v instanceof Element) {
          // 递归渲染
          render(v, el)
        } else {
          const textNode = document.createTextNode(v)
          el.appendChild(textNode)
        }
      })

      root.appendChild(el)
    }

    function setAttr(key, value, el) {
      switch (key) {
        // 业务处理
        // classname  直接添加类名
        case 'className':
          if(Array.isArray(value)) {
            value.forEach(v => {
              el.classList.add(v)
            })
          } else if (Object.prototype.toString.call(value) === '[object Object]') {
            Object.entries(value).forEach(([key, value]) => {
              value && el.classList.add(key)
            })
          } else {
            el.classList.add(value)
          }
          return
        default:
          el.setAttribute(key, value)
      }
    }

    const virtaulDom = createElement('h1', { className: 'active', id: '12312313534', style: 'background-color: red;' }, [
      '今天天气不错',
      createElement('b', { title: '哈哈哈，我是B标题' }, ['嘻嘻']),
      createElement('span', { className: ['a', 'b', 'c'] }, ['呵呵']),
      createElement('a', { className: { active: true, active1: false }, href: 'http://www.baidu.com' }, ['点我去百度']),
    ])

    console.log(virtaulDom);
    render(virtaulDom, document.querySelector('#app'))

  </script>
</body>

</html>